package com.yzmoney.wechat.service;

import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.model.JsonResult;
import com.yzmoney.common.util.HttpClientUtil;
import com.yzmoney.common.util.JDKStackTrace;
import com.yzmoney.common.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 通讯录的行为操作
 *
 * @author DOVE
 */
@Component
public class WechatContactsService {
    private static Logger logger = Logger.getLogger(WechatContactsService.class);
    private static String baseQYHUserUrl = PropertyUtils.getValue("CONTACTS_URL", "",
            Constants.QYH_PATH);
    private String errorCode = "60111";// 用户不存在

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    public WechatContactsService() {
        super();
    }

    /**
     * 创建和修改通讯录成员
     *
     * @param templateMsg json格式的用户信息
     * @param operate     需要操作的用户行为 (添加>create，修改update)
     * @return
     */
    public JsonResult userOperate(String templateMsg, String operate) {
        JsonResult jsonResult = new JsonResult();
        String accessToken = wechatAccessTokenService.getQYHAccessToken();

        if (StringUtils.isEmpty(accessToken)) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("获取accessToken error");
            return jsonResult;
        }
        String url = getUserUrl(accessToken, operate);

        if (StringUtils.isEmpty(url)) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("请求发送模版地址为空，请联系管理员");
            return jsonResult;
        }
        String result = HttpClientUtil.post(url, templateMsg, "UTF-8");
        logger.info(Constants.LOGPRIFIX + "Url：" + url + ",operate：" + operate + ", result：" + result);
        Map<String, Object> map = JsonUtils.toObject(result, Map.class);
        if (map == null) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("获取返回值为空");
            return jsonResult;
        }
        Object errCodeObj = map.get("errcode");
        Object errMsgObj = map.get("errmsg");
        if (errCodeObj == null) {
            logger.info(Constants.LOGPRIFIX + "get result for errCode null ");
            jsonResult.setCode(100);
            jsonResult.setMsg("返回结果出错，获取不到errcode");
            return jsonResult;
        }
        if (errMsgObj == null) {
            logger.info(Constants.LOGPRIFIX + "get result for errmsg null ");
            jsonResult.setCode(100);
            jsonResult.setMsg("返回结果出错，获取不到errmsg");
            return jsonResult;
        }
        String errCode = errCodeObj.toString();
        String errMsg = errMsgObj.toString();
        logger.info(Constants.LOGPRIFIX + "accessToken=" + accessToken + "errCode:" + errCode
                + " ,errMsg:" + errMsg);
        if (errCode.equals("0")) {
            jsonResult.setCode(Constants.CODE_SUCCESS);
        } else if (errCode.equals(errorCode)) {
            jsonResult.setCode(60111);
            jsonResult.setMsg(errMsg);
        } else {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg(errMsg);
        }
        logger.info(Constants.LOGPRIFIX + " jsonResult:" + jsonResult);
        return jsonResult;
    }

    /**
     * 删除用户
     *
     * @param userId  用户编号
     * @param operate 用户行为-删除
     * @return
     */
    public JsonResult userDelete(String userId, String operate) {
        String accessToken = wechatAccessTokenService.getQYHAccessToken();
        String url = getUserUrl(accessToken, operate);
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isEmpty(url)) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("请求发送模版地址为空，请联系管理员");
            return jsonResult;
        }
        url = url + "&userid=" + userId;
        try {

            String result = HttpClientUtil.get(url, null, "UTF-8");
            Map<String, Object> map = JsonUtils.toObject(result, Map.class);
            if (map == null) {
                jsonResult.setCode(Constants.CODE_FAILURE);
                jsonResult.setMsg("获取返回值为空");
                return jsonResult;
            }
            Object errCodeObj = map.get("errcode");
            Object errMsgObj = map.get("errmsg");
            if (errCodeObj == null) {
                logger.info(Constants.LOGPRIFIX + "get result for errCode null ");
                jsonResult.setCode(100);
                jsonResult.setMsg("返回结果出错，获取不到errcode");
                return jsonResult;
            }
            if (errMsgObj == null) {
                logger.info(Constants.LOGPRIFIX + "get result for errmsg null ");
                jsonResult.setCode(100);
                jsonResult.setMsg("返回结果出错，获取不到errmsg");
                return jsonResult;
            }
            String errCode = errCodeObj.toString();
            String errMsg = errMsgObj.toString();
            logger.info(Constants.LOGPRIFIX + "accessToken=" + accessToken + "errCode:" + errCode
                    + " ,errMsg:" + errMsg);
            if (errCode.equals("0")) {
                jsonResult.setCode(Constants.CODE_SUCCESS);
            } else if (errCode.equals(errorCode)) {
                jsonResult.setCode(60111);
                jsonResult.setMsg(errMsg);
            } else {
                jsonResult.setCode(Constants.CODE_FAILURE);
                jsonResult.setMsg(errMsg);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.debug(JDKStackTrace.getJDKStrack(e));
        }
        return jsonResult;
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @param operate
     * @return
     */
    public JsonResult getUser(String userId, String operate) {
        String accessToken = wechatAccessTokenService.getQYHAccessToken();
        String url = getUserUrl(accessToken, operate);
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isEmpty(url)) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("请求发送模版地址为空，请联系管理员");
            return jsonResult;
        }
        url = url + "&userid=" + userId;
        logger.info(Constants.LOGPRIFIX + "get user by userId:" + userId);
        try {
            String result = HttpClientUtil.get(url, null, "UTF-8");
            logger.info(Constants.LOGPRIFIX + "Url：" + url + " result：" + result);
            Map<String, Object> map = JsonUtils.toObject(result, Map.class);
            if (map == null) {
                jsonResult.setCode(Constants.CODE_FAILURE);
                jsonResult.setMsg("获取返回值为空");
                return jsonResult;
            }
            Object errCodeObj = map.get("errcode");
            Object errMsgObj = map.get("errmsg");
            if (errCodeObj == null) {
                logger.info(Constants.LOGPRIFIX + "get result for errCode null ");
                jsonResult.setCode(100);
                jsonResult.setMsg("返回结果出错，获取不到errcode");
                return jsonResult;
            }
            if (errMsgObj == null) {
                logger.info(Constants.LOGPRIFIX + "get result for errmsg null ");
                jsonResult.setCode(100);
                jsonResult.setMsg("返回结果出错，获取不到errmsg");
                return jsonResult;
            }
            String errCode = errCodeObj.toString();
            String errMsg = errMsgObj.toString();
            logger.info(Constants.LOGPRIFIX + "accessToken=" + accessToken + "errCode:" + errCode
                    + " ,errMsg:" + errMsg);
            if (errCode.equals("0")) {
                jsonResult.setCode(Constants.CODE_SUCCESS);
            } else if (errCode.equals(errorCode)) {
                jsonResult.setCode(60111);
                jsonResult.setMsg(errMsg);
            } else {
                jsonResult.setCode(Constants.CODE_FAILURE);
                jsonResult.setMsg(errMsg);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.debug(JDKStackTrace.getJDKStrack(e));
        }
        return jsonResult;
    }

    private String getUserUrl(String accessToken, String action) {

        if (StringUtils.isEmpty(accessToken)) {
            return null;
        }
        String url = baseQYHUserUrl + "/" + action + "?access_token=" + accessToken;
        return url;
    }

}
